package org.homerepair

import org.apache.commons.lang.builder.HashCodeBuilder

class ClientUserClientRole implements Serializable {

	ClientUser clientUser
	ClientRole clientRole

	boolean equals(other) {
		if (!(other instanceof ClientUserClientRole)) {
			return false
		}

		other.clientUser?.id == clientUser?.id &&
			other.clientRole?.id == clientRole?.id
	}

	int hashCode() {
		def builder = new HashCodeBuilder()
		if (clientUser) builder.append(clientUser.id)
		if (clientRole) builder.append(clientRole.id)
		builder.toHashCode()
	}

	static ClientUserClientRole get(long clientUserId, long clientRoleId) {
		find 'from ClientUserClientRole where clientUser.id=:clientUserId and clientRole.id=:clientRoleId',
			[clientUserId: clientUserId, clientRoleId: clientRoleId]
	}

	static ClientUserClientRole create(ClientUser clientUser, ClientRole clientRole, boolean flush = false) {
		new ClientUserClientRole(clientUser: clientUser, clientRole: clientRole).save(flush: flush, insert: true)
	}

	static boolean remove(ClientUser clientUser, ClientRole clientRole, boolean flush = false) {
		ClientUserClientRole instance = ClientUserClientRole.findByClientUserAndClientRole(clientUser, clientRole)
		if (!instance) {
			return false
		}

		instance.delete(flush: flush)
		true
	}

	static void removeAll(ClientUser clientUser) {
		executeUpdate 'DELETE FROM ClientUserClientRole WHERE clientUser=:clientUser', [clientUser: clientUser]
	}

	static void removeAll(ClientRole clientRole) {
		executeUpdate 'DELETE FROM ClientUserClientRole WHERE clientRole=:clientRole', [clientRole: clientRole]
	}

	static mapping = {
		id composite: ['clientRole', 'clientUser']
		version false
	}
}
